package cn.android666.recorddemowithnoise

import android.app.Activity
import android.app.AlertDialog

object UiUtil {

    private var dialog: AlertDialog? = null

    fun cancelDialog() {
        try {
            if (dialog?.isShowing == true) {
                dialog?.cancel()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun showOneButtonDialog(
        activity: Activity,
        message: CharSequence,
        title: CharSequence = activity.getString(R.string.warm_prompt),
        okButtonName: CharSequence = activity.getString(R.string.confirm),
        okButtonClick: (() -> Unit)? = null) {

        if (activity.isFinishing) {
            return
        }

        if (dialog?.isShowing == true) {
            dialog?.cancel()
        }

        dialog = AlertDialog.Builder(activity)
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton(okButtonName) { _, _ -> okButtonClick?.invoke(); dialog = null }
            .setCancelable(false)
            .show()
    }

    fun showTwoButtonDialog(
        activity: Activity,
        message: CharSequence,
        title: CharSequence = activity.getString(R.string.warm_prompt),
        okButtonName: CharSequence = activity.getString(R.string.confirm),
        okButtonClick: (() -> Unit)? = null,
        noButtonName: CharSequence = activity.getString(R.string.cancel),
        noButtonClick: (() -> Unit)? = null) {

        if (activity.isFinishing) {
            return
        }

        if (dialog?.isShowing == true) {
            dialog?.cancel()
        }

        dialog = AlertDialog.Builder(activity)
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton(okButtonName) { _, _ -> okButtonClick?.invoke(); dialog = null }
            .setNegativeButton(noButtonName) { _, _ -> noButtonClick?.invoke(); dialog = null }
            .setCancelable(false)
            .show()
    }

}